    var socket;
    var page_fire
    function OnSocket(){
        // socket = io("ws://" + RoomInfo.TServer + ":" + RoomInfo.TSPort);
        // socket.on('connect', function() {
        //     onConnect();
        // });
        // socket.on('message', function(data) {
        //     WriteMessage(data);
        // });

        connect();

        $("#form_article").keydown(function(){
            if(event.keyCode == "13"){
                MsgSend();
            }
        })

        var _body = document.querySelector("body");
        window.addEventListener("focusin", function () {
        });
        window.addEventListener("focusout", function () {});

    }
    function Datetime(tag)
    {
        return new Date().toTimeString().split(' ')[tag];
    }
    function MsgAutoScroll(){
        if($('#chatList').find(".msg_li").length>30){$('#chatList').find(".msg_li:first").remove();}
        $('#chatList').animate({scrollTop:$('#chatList')[0].scrollHeight}, 1000);
    }
    UserList=(function(){
        var list=[];
        list['ALL']={sex:2,chatid:'ALL',nick:'大家'}
        return{
            List:function(){return list},
            init:function(){
                list['ALL']={sex:2,chatid:'ALL',nick:'大家'}
                var request_url='../../ajax.php?act=getrlist&rid='+My.rid+'&r='+RoomInfo.r+'&'+Math.random() * 10000;
                $.ajax({type: 'get',dataType:'text',url: request_url,
                    success:function(data){
                        WriteMessage(data);
                    }});
                },
            get:function(id){return list[id];},
            add:function(id,u){
                if($("#"+id).length >0)return;
                list[id]=u;
            },
            del:function(id,u){
                if(id==My.chatid)return;
                delete(list[id]);
            }
        }
    })();
    function MsgShow(str,type){
        str='<li class="chat-item"><div class="message">'+str+'</div></li>';
        $("#chatList ul").append(str);
        MsgAutoScroll();
    }

    function MsgSend(){

            if(des_msg&&!check_auth("room_admin")){
                layer.open({
                    content: '禁止发言！',
                    style: 'background-color:#CCC; color:#000; border:none;',
                    time: 2
                });
                return false;
            }

            if (!check_auth("msg_send")) {
                layer.open({
                    content: '没有发言权限！',
                    style: 'background-color:#CCC; color:#000; border:none;',
                    time: 2
                });
                return false;
            }

            var med_t = $('#form_article').html();
            if(med_t.length <= 0 || med_t =='说点什么...'){
                layer.open({
                    content: '请写入您要发表的内容！',
                    style: 'background-color:#CCC; color:#000; border:none;',
                    time: 2
                });
                return false;
            }

            //过滤图片字符串
            var maxstr= med_t.replace(/<img.*>/ig,'-');
            if(maxstr.length>20){
                if (!check_auth("room_admin")){
                    layer.open({
                        content: '评论最大长度为20！',
                        style: 'background-color:#CCC; color:#000; border:none;',
                        time: 2
                    });
                    return false;
                }
            }

            var msgid=randStr()+randStr();
            var str=encodeURIComponent($("#form_article").html().str_replace());

            var Txt=decodeURIComponent(str.str_replace(My.qx));
            if(Txt.indexOf("含敏感关键字") >= 0 ){
                layer.open({
                    content: '含敏感关键字！',
                    style: 'background-color:#CCC; color:#000; border:none;',
                    time: 2
                });
                return false;
            }

            // var msgstr = 'SendMsg=M=ALL|false|font-weight:;font-style:; text-decoration:;color:rgb(0, 0, 0); font-family:; font-size:12pt|'+msgid+'_+_'+str+'|'+My.qx;
            // socket.emit('message', msgstr);

            ws.send('{"type":"say","touser":"ALL","IsPersonal":"false","Style":"'+'font-weight:;font-style:; text-decoration:;color:rgb(0, 0, 0); font-family:; font-size:12pt'+'","Msg":"'+ msgid + '_+_' + str +'","qx":"'+My.qx+'"}');

            PutMessage(My.rid,My.chatid,'ALL',My.nick,'大家','false','',str,msgid);
            $("#form_article").html("");
            $(".footer").removeClass("showPhiz");
            MsgAutoScroll();

            return false;
    }
    function randStr(){
        return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
    }
    function PutMessage(rid,uid,tid,uname,tname,privacy,style,str,msgid){
        if(RoomInfo.Msglog=='0')return;
        var request_url='../../ajax.php?act=putmsg';
        var postdata='msgid='+msgid+'&uname='+uname+'&tname='+tname+'&muid='+uid+'&rid='+rid+'&tid='+tid+'&privacy='+privacy+'&style='+style+'&msg='+str+'&'+Math.random() * 10000;

        $.ajax({type: 'POST',url:request_url,data:postdata});
    }
    function Mkick(adminid,rid,ktime,cause)
    {
        $.ajax({type: 'get',dataType:'json',url: '../../ajax.php?act=kick&aid='+adminid+'&rid='+rid+'&ktime='+ktime+'&cause='+cause+'&u='+My.name+'&'+Math.random() * 10000,
                success:function(data){
                    //alert(data);
                    if(data.state=="yes"){
                    location.href="../error.php?msg="+encodeURI('你被踢出！并禁止'+ktime+'分钟内登陆该房间！<br>原因是 '+cause+'');
                    }
                }
        });
    }

    String.prototype.str_replace=function(qx){
            var str=this;

            var reg = new RegExp(msg_unallowable, "ig");

            if(!qx){
                var mystr= str.replace(/<img.*>/ig,'');

                if(reg.test(mystr)&&(!check_auth("room_admin")))
                {
                    return "含敏感关键字，内容被屏蔽";
                }

                str= str.replace(/<\/?(?!br|img|font|p|span|\/font|\/p|\/span)[^>]*>/ig,'').replace(/\r?\n/ig,' ').replace(/(&nbsp;)+/ig," ").replace(/(=M=)+/ig,"").replace(/(|)+/ig,"").replace(/(SendMsg)/ig,'');

                //if(!check_auth("room_admin"))str=str.replace(reg,'**')
                return str;
            }

            return str;
    };

    function check_auth(auth){
        var auth_rules = grouparr[My.color].rules;
        if(auth_rules.indexOf(auth)>-1)return true;
        else false;
    }
    function remove_auth(auth) {
        grouparr[My.color].rules = grouparr[My.color].rules.replace(auth, "");
    }
    function kick_send(adminid)
    {
        $.ajax({type: 'get', dataType: 'json', url: '../../ajax.php?act=kick_send&aid='+adminid+'&u=' + encodeURIComponent(My.name) + '&' + Math.random() * 10000,

        });
    }
    function FormatMsg(Msg)
    {
        var User=UserList.get(Msg.ChatId);
        var toUser=UserList.get(Msg.ToChatId);
        var date= Datetime(0);
        var IsPersonal='';

        // if(typeof(User)=='undefined'||typeof(toUser)=='undefined')return false;

        if ( typeof (toUser) == 'undefined'){
            return false;
        }
        //机器人格式话
        if(typeof (User) == 'undefined' ){
            var ss = new Array();
            for(var pro in grouparr) {
                if(pro != '2' &&  pro != '0'&&  pro != '4' ){
                    ss.push(pro);
                }
            }
            var num = parseInt(Math.random() * ss.length);

            User = {chatid: "123456", color: ss[num], ip: "127.0.0.1", mood: "", nick: randomWord(true, 6, 9),qx:"0",roomid:"1",sex:"0",state:"0",vip:ss[num]}
        }

        if(Msg.IsPersonal=='true' && toUser.chatid!='ALL') IsPersonal='[私]';


        var Txt=decodeURIComponent(Msg.Txt.str_replace(My.qx));
        if(Txt.indexOf("含敏感关键字") >= 0 ){
            return false;
        }


        if(Txt.indexOf('C0MMAND')!=-1)
        {
            var command=Txt.split('_+_');
            switch(command[1])
            {
                case 'send_Msgblock':
                    if (My.chatid == toUser.chatid) {
                        remove_auth('msg_send');
                        layer.open({
                            content: '你已被禁言！',
                            style: 'background-color:#CCC; color:#000; border:none;',
                            time: 2
                        });
                        kick_send(Msg.ChatId);
                    }
                    return 'yyc';
                case 'msgAudit':
                    $('#'+command[2]).show();
                    MsgAutoScroll();
                    $.ajax({type: 'get',url: '../../ajax.php?act=msgblock&s=0&msgid='+command[2]});
                break;
                case 'msgBlock':
                    $('#'+command[2]).remove();
                    MsgAutoScroll();
                    $.ajax({type: 'get',url: '../../ajax.php?act=msgblock&s=1&msgid='+command[2]});
                break;
                case 'rebotmsg':
                    var msg={};
                    msg.ChatId=command[2];
                    msg.ToChatId='ALL';
                    msg.IsPersonal='false';
                    msg.Txt=command[3];
                    msg.Style=Msg.Style;
                    MsgShow(FormatMsg(msg),0);
                break;

                case 'kick':


                    if(My.chatid==toUser.chatid){
                        Mkick(Msg.ChatId,My.roomid,command[2],command[3]);
                    }
                break;
            }
        }
        else
        {
            var msgid="";
            if(Txt.indexOf('_+_')>-1){
                var t=Txt.split('_+_');
                msgid= t[0];
                Txt=t[1];
            }


            //表情不需要审核
            var str = Txt;
            str = decodeURIComponent(str);
            var res1 = /<img src="\/room\/face\/colorbar\/[a-z]{2,6}.gif">/i.test(str);
            var res2 = /(<img src="\/room\/face\/pic\/[0-9a-z_]{2,11}.gif">){8}/i.test(str);
            var res3 = /<img src="\/room\/skins\/chatimg\/[A-Za-z][A-Za-z]*/i.test(str);

            var  msgAuditShow = "";
            if (RoomInfo.msgAudit == "1" && (!res1 && !res2 && !res3) && Msg.qx != '1' ) {
                msgAuditShow = 'style="display:none"';
                if (check_auth('msg_audit')) {
                    msgAuditShow = "";
                }
                if (User.chatid == My.chatid)
                    msgAuditShow = "";
            }

            var str="<div "+msgAuditShow+">";

            str+='<span class="chat-tag-user-level icon-level-12"><img src="'+grouparr[User.color].ico+'" class="msg_group_ico" title="'+grouparr[User.color].title+'"></span>';
            str+='<span class="chat-user-name">'+User.nick+':</span>';
            str+='<span class="chat-content">'+Txt+'</span>';

            str+='</div>';

        }


        return str;

    }
    function WriteMessage(txt){

        var Msg;
        try{
            Msg=eval("("+txt+")");
        }catch(e){return;}
        if(Msg.stat!='OK')
        {

            if (Msg.stat == "des_msg") {
                if(globalgid ==Msg.roomid ){
                    des_msg = Msg.des_msg;
                }
                return;
            }
            if(Msg.stat=="MaxOnline"){
                document.body.innerHTML='<div  style="font-size:12px; text-align:center; top:100px; position:absolute;width:100%">O.O 对不起，服务端并发数已满！请您联系管理员对系统扩容升级！<br><br></div>';
                return;
                }
            return ;
        }
        switch(Msg.type)
        {
            case "Ulogin":
                var U=Msg.Ulogin;
                var vip_msg="到来";
                var date= Datetime(0);
                var str='<span class="info">欢迎：<font class="u" onclick="ToUser.set(\''+U.chatid+'\',\''+U.nick+'\')">'+U.nick+'</font>  <font class="date">'+date+'</font></span>';
                if(My.chatid!=U.chatid){
                UserList.add(U.chatid,U);
                }
                var type=0;
                if(U.chatid==My.chatid) type=2;

            break;
            case "UMsg":

                var str=FormatMsg(Msg.UMsg);

                if(!str){
                    return false;
                }


                if(str != 'yyc') {
                    MsgShow(str,1);
                }
            break;
            case "UonlineUser":

                var onlineNum=Msg.roomListUser.length;
                for(i=0;i<onlineNum;i++)
                {
                var U=Msg.roomListUser[i];

                UserList.add(U.chatid,U);
                }
            break;
            case "Ulogout":
                var U=Msg.Ulogout;
                var date= Datetime(0);
                var str='<span class="info">用户：'+U.nick+'   离开！ <font class="date">'+date+'</font></span>';
                //MsgShow(str,0);
                UserList.del(U.chatid,U);
            break;
            case "SPing":
                //alert(Msg.SPing.time);
            break;
            case "Sysmsg":
                alert(Msg.Sysmsg.txt);
            break;
        }

    }
    function OnInit(){
        Init();
        showLive();
        MsgAutoScroll();
        OnSocket();
        $("#sendBtn").click(function(){MsgSend();});
        $('#chatList').height($(window).height()-266)
    }
    function onConnect()
    {
        // var str='Login=M='+My.roomid+'|'+My.chatid+'|'+My.nick+'|'+My.sex+'|'+My.age+'|'+My.qx+'|'+My.ip+'|'+My.vip+'|'+My.color+'|'+My.cam+'|'+My.state+'|'+My.mood;
        // socket.emit('message', str);
        // if(typeof(UserList)!='undefined'){
        //     UserList.init();
        // }
    }
    function icon3() {
            var a = $("head  title").text();
            postToWb(a)
    }
    function icon2() {
            var a = $("head  title").text();
            postToXinLang(a)
    }
    function icon4() {
            var a = $("head  title").text();
            postToQzone(a)
    }
    function postToXinLang(a) {
        window.open("http://v.t.sina.com.cn/share/share.php?title=" + encodeURIComponent(a) + "&url=" + encodeURIComponent(location.href) + "&rcontent=", "_blank", "scrollbars=no,width=600,height=450,left=75,top=20,status=no,resizable=yes")
    }
    function postToQzone(a) {
        var b = encodeURI(a),
        c = encodeURI(a),
        d = encodeURI(document.location);
        return window.open("http://sns.qzone.qq.com/cgi-bin/qzshare/cgi_qzshare_onekey?title=" + b + "&url=" + d + "&summary=" + c),
        !1
    }
    function postToWb(a) {
        var b = encodeURI(a),
        c = encodeURI(document.location),
        d = encodeURI(""),
        e = encodeURI(""),
        f = "",
        g = "http://v.t.qq.com/share/share.php?title=" + b + "&url=" + c + "&appkey=" + d + "&site=" + f + "&pic=" + e;
        window.open(g, "转播到腾讯微博", "width=700, height=680, top=0, left=0, toolbar=no, menubar=no, scrollbars=no, location=yes, resizable=no, status=no")
    }



    function showLive(){
        $("#video-win").html('<iframe height="230" width="100%" allowTransparency="true" marginwidth="0" marginheight="0"  frameborder="0" scrolling="no" src="../player.php?type=m&rid='+globalgid+'"></iframe>');
    }
    function Init(){
        // $('#chatList').height($(window).height()-$('.room-matrix').height());

        $("#video-flash").click(function(){showLive()});
    $("body").click(function() { $(".setting-expression-layer").hide() });
    $(".cmt-phiz").click(function(a) {
        if($('.footer').hasClass('showPhiz')){
            $('.footer').removeClass('showPhiz');
        }else {
            $('.footer').addClass('showPhiz');
        }
    });

    }

    function getmsg(){
       $.ajax({type: 'get',dataType:'text',url: 'ajax.php?act=getmsg',
                    success:function(data){
                        $("#publicChat").append(data);
        MsgAutoScroll();
                    }});
    }
    function orient() {
        if (window.orientation == 90 || window.orientation == -90) {
    //ipad、iphone竖屏；Andriod横屏
            $("body").attr("class", "landscape");
            orientation = 'landscape';
            return false;
        }
        else if (window.orientation == 0 || window.orientation == 180) {
    //ipad、iphone横屏；Andriod竖屏
            window.location.href='./';
            $("body").attr("class", "portrait");
            orientation = 'portrait';
            return false;
        }
    }

    $(function(){
        window.onresize = function(){
            $('#chatList').height($(window).height()-$('.room-matrix').height());
        }
    });
    $(window).bind( 'orientationchange', function(e){
        orient();
    });


    //phpwebsocket
    function connect() {
        // 创建websocket
        ws = new WebSocket("ws://" + RoomInfo.TServer + ":" + RoomInfo.TSPort);
        // 当socket连接打开时，输入用户名
        ws.onopen = onopen;
        // 当有消息时根据消息类型显示不同信息
        ws.onmessage = onmessage;
        ws.onclose = function() {
            console.log("连接关闭，定时重连");
            setTimeout("connect()",10000);
        };
        ws.onerror = function() {
            console.log("出现错误");
        };
    }

    // 连接建立时发送登录信息
    function onopen()
    {
        name = My.nick;
        if(!name)
        {
            show_prompt();
        }

        if (typeof (UserList) != 'undefined') {
            UserList.init();
        }
        // 登录
        var login_data = '{"type":"login","client_name":"'+name.replace(/"/g, '\\"')+'","room_id":"'+My.roomid+'","uid":"'+My.chatid+'","color":"'+My.color+'","qx":"'+My.qx+'"}';
        console.log("websocket握手成功，发送登录数据:"+login_data);
        ws.send(login_data);
    }

    // 服务端发来消息时
    function onmessage(e) {
        var data = eval("(" + e.data + ")");
        console.log(data);
        switch (data['type']) {
            // 服务端ping客户端
            case 'ping':
                ws.send('{"type":"pong"}');
                break;
                ;
            // 登录
            case 'login':
                var U = data;
                var vip_msg="到来";
                var date= Datetime(0);
                var str='<span class="info">欢迎：<font class="u" onclick="ToUser.set(\''+U.chatid+'\',\''+U.nick+'\')">'+U.nick+'</font>  <font class="date">'+date+'</font></span>';
                if(My.chatid!=U.chatid){
                    UserList.add(U.chatid,U);
                }
                var type=0;
                if(U.chatid==My.chatid) type=2;

                console.log(data['nick'] + "登录成功");
                break;
            // 异地登录
            case 'otherLogin':
                location.href = "error.php?msg=" + encodeURI('其他地方登录！请注意同一帐号不能两处登录、同一电脑不能两处打开房间！')
                break;
            // 登录-更新用户列表
            case 'initUserList':
                client_list = data['client_list'];
                flush_client_list();
                break;
            // 发言
            case 'say':

                var str=FormatMsg(data);

                if(!str){
                    return false;
                }
                if(str != 'yyc') {
                    MsgShow(str,1);
                }

                break;
            // 用户退出 更新用户列表
            case 'logout':
                var U = data;
                console.log('退出登录');
                console.log(data);
                if (U.chatid == '-1' || U.chatid == '-2')
                    return;
                UserList.del(U.chatid, U);
                break;
            // 送礼物
            case 'send_gif':
                $('#gift_super').attr('data', 'skins/gift/' + data.data_str.gift_id + '_188.swf');
                $('#gifcontainer').show();
                rideHorse(data.data_str.nick + '送出' + data.data_str.gift_name + 'x' + data.data_str.num);
                setTimeout("$('#gifcontainer').hide()", 10000);
                break;
            case 'des_msg':

                if (globalgid == data.roomid) {
                    des_msg = data.des_msg;
                }
                break;
            //更新机器人
            case 'set_robot':
                if (globalgid == data.roomid) {
                    var OnlineUserNum = getId('OnlineUserNum');
                    var RealUserNum = getId('RealUserNum').innerHTML;
                    OnlineUserNum.innerHTML = parseInt(RealUserNum) + parseInt(data.robot_num);
                }
                break;
            //维护
            case 'MaxOnline':
                document.body.innerHTML = '<div  style="font-size:12px; text-align:center; top:100px; position:absolute;width:100%">O.O 对不起，服务端并发数已满！请您联系管理员对系统扩容升级！<br><br></div>';
                break;
            //充值
            case 'recharge':
                if (globalgid == data.roomid) {
                    //充值
                    My.diamond = parseInt(My.diamond)+parseInt(data.cost);
                }
                break;
            //踢人
            case 'kick':
                location.href = "/room/error.php?msg=" + encodeURI('你被踢出！并禁止' + data.ktime + '分钟内登陆该房间！<br>原因是 ' + data.cause + '');
                break;
        }
    }
    // 输入姓名
    function show_prompt(){
        // name = prompt('输入你的名字：', '');
        if(!name || name=='null'){
            name = '新人';
        }
    }

    // 提交对话
    function onSubmit() {
        var input = document.getElementById("textarea");
        var to_client_id = $("#client_list option:selected").attr("value");
        var to_client_name = $("#client_list option:selected").text();
        ws.send('{"type":"say","to_client_id":"'+to_client_id+'","to_client_name":"'+to_client_name+'","content":"'+input.value.replace(/"/g, '\\"').replace(/\n/g,'\\n').replace(/\r/g, '\\r')+'"}');
        input.value = "";
        input.focus();
    }

    // 刷新用户列表框
    function flush_client_list(){
        var onlineNum = client_list.length;
        for (i = 0; i < onlineNum; i++)
        {
            var U = client_list[i];
            if(U.chatid == '-1' || U.chatid == '-2')
                continue;
            UserList.add(U.chatid, U);
        }

        $("#client_list").val(select_client_id);
    }

    $(function(){
        select_client_id = 'all';
        $("#client_list").change(function(){
            select_client_id = $("#client_list option:selected").attr("value");
        });



    });



    /*
    ** randomWord 产生任意长度随机字母数字组合
    ** randomFlag-是否任意长度 min-任意长度最小位[固定位数] max-任意长度最大位
    ** xuanfeng 2014-08-28
    */

    function randomWord(randomFlag, min, max){
        var str = "",
            range = min,
            arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];

        // 随机产生
        if(randomFlag){
            range = Math.round(Math.random() * (max-min)) + min;
        }
        for(var i=0; i<range; i++){
            pos = Math.round(Math.random() * (arr.length-1));
            str += arr[pos];
        }
        return str;
    }
